<template>
  <div class="dateselect">
    <div
      v-for="(item, index) in times"
      :key="item.type"
      style="position: relative"
    >
      <div
        class="dateslect-title"
        :class="{ selected: item.type == checkedTitle }"
        @click="changeDateTitle(item)"
      >
        <span style="vertical-align: middle">{{ item.name }}</span
        ><a-icon
          :type="
            item.type == checkedTitle && showItem ? 'caret-up' : 'caret-down'
          "
          style="vertical-align: middle"
        />
      </div>
      <ul
        v-show="item.type == checkedTitle && showItem"
        class="dateselect-other"
      >
        <li
          v-for="(jtem, jndex) in item.othertime"
          :key="jtem.title"
          class="other-li"
          :class="{ otherselect: checkedItem == jndex }"
          @click="changeOtherDate(item, index, jtem, jndex)"
        >
          {{ jtem.title }}
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import moment from 'moment';
export default {
  name: 'timeQuantumSelect',
  components: {},
  computed: {},
  props: {
    // 标题选择
    titles: {
      type: Array,
      default: () => ['hour', 'day', 'week', 'month'],
    },
    days: {
      type: Number,
      default: () => 12,
    },
    weeks: {
      type: Number,
      default: () => 7,
    },
    months: {
      type: Number,
      default: () => 5,
    },
  },
  data() {
    return {
      times: [],
      checkedTitle: '',
      checkedItem: 0,
      showItem: false,
    };
  },
  watch: {},
  created() {},
  mounted() {
    this.updateTimes();
  },
  beforeDestroy() {},
  methods: {
    dateChange() {
      this.$emit('change', this.getDate());
    },
    getDate() {
      const index = this.titles.indexOf(this.checkedTitle);
      const { val, chartTitle } = this.times[index].othertime[this.checkedItem];
      if (this.checkedTitle === 'hour') {
        const end = moment();
        const start = moment(end).subtract(val, 'hour');
        return {
          start: start.valueOf(),
          end: end.valueOf(),
          chartTitle,
          type: this.checkedTitle,
        };
      } else {
        return { ...val, chartTitle, type: this.checkedTitle };
      }
    },
    updateTimes() {
      if (this.titles.length == 0) {
        console.warn('标题不能为空');
        return;
      }
      if (this.titles.indexOf('day') !== -1) {
        this.checkedTitle = 'day';
      } else {
        this.checkedTitle = this.titles[0];
      }
      const times = [];
      this.titles.forEach((item) => {
        let othertime;
        switch (item) {
          case 'hour':
            othertime = this._getHourlist();
            break;
          case 'day':
            othertime = this._getDaylist();
            break;
          case 'week':
            othertime = this._getWeekList();
            break;
          case 'month':
            othertime = this._getMonthList();
            break;
        }
        times.push({
          type: item,
          name: othertime[0].show,
          othertime: othertime,
        });
      });
      this.times = times;
      this.checkedItem = 0;
    },
    changeDateTitle(item) {
      if (this.checkedTitle === item.type) {
        //打开关闭 子项
        this.showItem = !this.showItem;
        return;
      }
      this.showItem = false;
      const index = this.titles.indexOf(this.checkedTitle);
      this.times[index].name = this.times[index].othertime[0].show;
      this.checkedTitle = item.type;
      this.checkedItem = 0;
      this.dateChange();
    },
    changeOtherDate(item, index, jtem, jndex) {
      this.checkedItem = jndex;
      item.name = jtem.show;
      this.showItem = false;
      this.dateChange();
    },
    /**
     * 获取小时列表
     */
    _getHourlist() {
      const HourList = [];
      HourList.push({
        title: this.$t('deviceDetail.last1Hour'),
        val: 1,
        show: this.$t('deviceDetail.1Hour'),
        chartTitle: this.$t('deviceDetail.last1Hour'),
      });
      HourList.push({
        title: this.$t('deviceDetail.last8Hour'),
        val: 8,
        show: this.$t('deviceDetail.8Hour'),
        chartTitle: this.$t('deviceDetail.last8Hour'),
      });
      HourList.push({
        title: this.$t('deviceDetail.last24Hour'),
        val: 24,
        show: this.$t('deviceDetail.24Hour'),
        chartTitle: this.$t('deviceDetail.last24Hour'),
      });
      HourList.push({
        title: this.$t('deviceDetail.last48Hour'),
        val: 48,
        show: this.$t('deviceDetail.48Hour'),
        chartTitle: this.$t('deviceDetail.last48Hour'),
      });
      return HourList;
    },
    /**
     * 获取日列表
     */
    _getDaylist() {
      const today = moment();
      const dayInterval = this.days;
      const dayList = [];
      const titleArr = [
        this.$t('deviceDetail.today'),
        this.$t('deviceDetail.yesterday'),
      ];
      for (let i = 0; i <= dayInterval; i++) {
        let title, showTitle;
        const day = moment(today).subtract(i, 'days');
        if (titleArr[i]) {
          title = titleArr[i] + ' ' + day.format('YYYY-MM-DD');
          showTitle = titleArr[i];
        } else {
          title = day.format('YYYY-MM-DD');
          showTitle = this.$t('deviceDetail.oneday');
        }
        const end = moment(day.format('YYYY-MM-DD 23:59:59'));
        //日区间取48小时
        const start = moment(
          moment(today)
            .subtract(i + 1, 'days')
            .format('YYYY-MM-DD 00:00:00')
        );
        dayList.push({
          title: title,
          val: { start: start.valueOf(), end: end.valueOf() },
          show: showTitle,
          chartTitle: `${start.format('YYYY-MM-DD')}~${end.format(
            'YYYY-MM-DD'
          )}`,
        });
      }
      return dayList;
    },
    /**
     * 获取周列表
     */
    _getWeekList() {
      const today = moment();
      const weekInterval = this.weeks;
      const titleArr = [
        this.$t('deviceDetail.week'),
        this.$t('deviceDetail.lastweek'),
      ];
      const weekList = [];
      for (let i = 0; i <= weekInterval; i++) {
        let title, showTitle;
        var day = moment(today).subtract(i, 'week');
        const weekNumber = moment(day).get('week'); //本周是一年中第几周
        const start = moment(day).startOf('week'); //本周开始时间
        const end = moment(day).endOf('week'); //本周结束时间
        const chartTitle = `${start.format('YYYY-MM-DD')}~${end.format(
          'YYYY-MM-DD'
        )}`;
        if (titleArr[i]) {
          title = `${titleArr[i]}（ ${chartTitle}）`;
          showTitle = titleArr[i];
        } else {
          title = this.$t('deviceDetail.selweekSelweek2', {
            weekNumber: weekNumber,
            chartTitle: chartTitle,
          });
          showTitle = weekNumber + this.$t('deviceDetail.selweek3');
        }
        weekList.push({
          title: title,
          val: { start: start.valueOf(), end: end.valueOf() },
          show: showTitle,
          chartTitle: chartTitle,
        });
      }
      return weekList;
    },
    /**
     * 获取月列表
     */
    _getMonthList() {
      const today = moment();
      const monthInterval = this.months;
      const titleArr = [
        this.$t('deviceDetail.month'),
        this.$t('deviceDetail.lastmonth'),
      ];
      const monthList = [];
      for (var i = 0; i <= monthInterval; i++) {
        let title, showTitle;
        var day = moment(today).subtract(i, 'month');
        const yearNumber = day.get('month') + 1; //本周是一年中第几月
        const start = moment(day).startOf('month'); //本月开始时间
        const end = moment(day).endOf('month'); //本月结束时间
        const chartTitle = moment(day).format('YYYY-M');
        if (titleArr[i]) {
          title = `${titleArr[i]} ${chartTitle}`;
          showTitle = titleArr[i];
        } else {
          title = `${chartTitle}`;
          showTitle = yearNumber + this.$t('dataInsight.month');
        }

        monthList.push({
          title: title,
          val: { start: start.valueOf(), end: end.valueOf() },
          show: showTitle,
          chartTitle: chartTitle,
        });
      }
      return monthList;
    },
  },
};
</script>

<style lang="less" scoped>
.dateselect {
  display: flex;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  .dateslect-title {
    padding: 0 10px;
    cursor: pointer;
    border-bottom: 1px solid #ccc;
    line-height: 28px;
    color: #0071eb;
    border-radius: 4px 4px 0 0;
  }
  .selected {
    border: 1px solid #ccc;
    border-bottom: none;
  }
  .dateselect-other {
    display: block;
    position: absolute;
    right: 0;
    background-color: #fff;
    box-shadow: 1px 1px 3px #333;
    padding: 10px 20px;
    z-index: 10;
    text-align: left;
    .other-li {
      white-space: nowrap;
      position: relative;
      line-height: 1.8;
      cursor: pointer;
    }
    .otherselect {
      color: #0071eb;
    }

    .otherselect::before {
      content: '';
      position: absolute;
      display: inline-block;
      width: 0;
      height: 0;
      margin-left: 2px;
      vertical-align: middle;
      border-left: 4px dashed;
      border-top: 4px solid transparent;
      border-bottom: 4px solid transparent;
      border-left-color: #0071eb;
      left: -10px;
      top: 50%;
      margin-top: -4px;
    }
  }
}
</style>
